package javaer.starter.core.parser;

import javaer.starter.base.domain.dto.ModuleDTO;
import javaer.starter.base.domain.dto.NewProjectDefinition;
import javaer.starter.base.domain.dto.PomParent;
import javaer.starter.base.service.ModuleService;
import javaer.starter.core.metadata.PomXml;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * module pom解析
 *
 * @author yangzhen
 * @date 2021/11/17 15:50
 * @since 1.0.0
 */
@Component
public class ModulePomXmlParser extends AbstractPomXmlParser {

    @Resource
    private ModuleService moduleService;

    @Override
    public PomXml initPom(NewProjectDefinition projectDefinition, ModuleDTO module) {
        return new PomXml()
                .setModuleId(module.getModuleId())
                .setImStarterPom(module.isStarter())
                .setGroupId(projectDefinition.getGroupId())
                .setArtifactId(getArtifactId(projectDefinition, module))
                .setBasePackage(projectDefinition.getBasePackage())
                .setDescription(projectDefinition.getDescription())
                .setModulePackage(getModulePackage(projectDefinition, module));
    }

    @Override
    public PomParent getParent(NewProjectDefinition projectDefinition) {
        PomParent pomParent = new PomParent();
        pomParent.setGroupId(projectDefinition.getGroupId());
        pomParent.setArtifactId(projectDefinition.getArtifactId());
        return pomParent;
    }

    @Override
    public Map<String, String> getProperties(NewProjectDefinition projectDefinition) {
        return null;
    }

    @Override
    public List<PomXml> parse(NewProjectDefinition projectDefinition) throws Exception {
        Set<ModuleDTO> moduleDTOS = moduleService.findByTypeId(projectDefinition.getTypeId());
        if (CollectionUtils.isEmpty(moduleDTOS)) {
            return null;
        }
        Set<String> moduleIds = Optional.ofNullable(projectDefinition.getModuleIds()).orElse(new HashSet<>());

        List<PomXml> pomXmlList = new ArrayList<>();
        for (ModuleDTO moduleDTO : moduleDTOS) {
            if (moduleDTO.isRequired() || moduleIds.contains(moduleDTO.getModuleId())) {
                PomXml pomXml = doBuild(projectDefinition, moduleDTO);
                pomXmlList.add(pomXml);
            }
        }
        return pomXmlList;
    }
}